
//引入express模块
const express = require("express");
//定义路由级中间件
const router = express.Router();
//引入数据模型模块
const Hero = require("../models/hero");

// 查询所有英雄信息路由
router.get("/hero", async (req, res) => {
  try {
    // 获取请求中的分页参数，默认值处理
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
        // 添加排序逻辑，这里假设按createdAt字段降序排序
        const sortOption = req.query.sortBy === 'asc' ? { createdAt: 1 } : { createdAt: -1 };
    // 计算跳过的文档数量
    const skip = (page - 1) * limit;
    const hero = await Hero.find().skip(skip).limit(limit).sort(sortOption);
    const total = await Hero.countDocuments();
    res.send({ data: hero, code: 200, message: "查询成功", pagination: { total, currentPage: page, limit } });
  } catch (err) {
    res.status(500).send({ error: 'Failed to retrieve hero' });
  }
});

// 通过name查询单个英雄信息路由
router.get("/hero/:name", async (req, res) => {
  try {
    const searchTerm = req.params.name;
    if (!searchTerm) {
      return res.status(400).send({ error: 'Search term is required' });
    }
    const hero = await Hero.find({ name: { $regex: searchTerm, $options: 'i' } });
    if (hero.length === 0) {
      return res.status(404).send({ message: 'No heros found with that name' });
    }
    res.send({ data: hero, code: 200, message: "查询成功" });
  } catch (err) {
    res.status(500).send({ error: 'Failed to retrieve hero' });
  }
});

// 添加一个英雄信息路由
router.post("/hero", async (req, res) => {
  //使用Hero model上的create方法储存数据
  try {
    const hreo = new Hero(req.body)
    await hreo.save();
    res.send({ message: "Hero created successfully" })
  } catch (err) {
    // 如果有错误，返回错误信息  
    res.status(500).json({ error: err.message });
  }
});

//更新一条英雄信息数据路由
router.put("/hero", async (req, res) => {
  try {
    const updatedHero = await Hero.findByIdAndUpdate(req.body.id, req.body, { new: true });
    if (!updatedHero) return res.status(404).send({ error: 'Hero not found' });
    res.send({message:"操作成功"});
  } catch (err) {
    res.status(500).send({ error: 'Failed to update hero' });
  }
});

// 添加图片路由
router.put("/addpic/:id", (req, res) => {
  Hero.findOneAndUpdate(
    { _id: req.params.id },
    {
      $push: {
        imgArr: req.body.url
      }
    },
    {
      new: true
    }
  )
    .then(hero => res.json(hero))
    .catch(err => res.json(err));
});

//删除一条英雄信息路由
router.delete("/hero", async (req, res) => {
  try {
    // 从查询参数中获取id
    const heroId = req.query.id;
    if (!heroId) {
      return res.status(400).send({ error: 'Missing "id" query parameter' });
    }

    await Hero.findByIdAndDelete(heroId);
    res.send({ message: 'Hero deleted successfully' });
  } catch (err) {
    if (err.name === 'CastError') return res.status(404).send({ error: 'Hero not found' });
    res.status(500).send({ error: 'Failed to delete hero' });
  }
});
module.exports = router

